﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;
using ComponentFactory.Krypton.Toolkit;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;

    public partial class UnitForm : Form
    {
        private class ColumnIndex
        {
            public const int Id = 0;
            public const int Name = 1;
        }

        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("UnitForm");
        private IRepository<Unit> unitRepository = null;
        private IList<Unit> listOfUnits = null;
        private IList<Unit> listOfUnitsToDelete = null;

        public UnitForm()
        {
            InitializeComponent();

            this.SetUp();
            this.LoadData();
        }

        /// <summary>
        /// Setup the data grid
        /// </summary>
        private void SetUp()
        {
            this.unitRepository = Program.Container.Resolve<IRepository<Unit>>();

            this.kdgvUnits.AutoGenerateColumns = false;
            var idColumn = new DataGridViewColumn
            {
                DataPropertyName = Unit.Properties.Id,
                Name = Unit.Properties.Id,
                HeaderText = "Id",
                ValueType = typeof(int),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = false,
            };
            this.kdgvUnits.Columns.Add(idColumn);

            var usernameColumn = new DataGridViewColumn
            {
                DataPropertyName = Unit.Properties.Name,
                Name = Unit.Properties.Name,
                HeaderText = "Unit Name",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 100,
            };
            this.kdgvUnits.Columns.Add(usernameColumn);
        }

        /// <summary>
        /// Load all units from database
        /// </summary>
        private void LoadData()
        {
            this.listOfUnits = this.unitRepository.FindAll();
            if (this.listOfUnits == null)
            {
                this.listOfUnits = new List<Unit>();
            }

            foreach (Unit unitItem in this.listOfUnits)
            {
                this.DisplayUnitData(unitItem);
            }
        }

        private DialogResult ConfirmRemoveUnits()
        {
            var result = DialogResult.None;
            if (this.kdgvUnits.SelectedRows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Are you sure you want to delete these units:");
                sb.AppendLine();
                foreach (DataGridViewRow rowItem in this.kdgvUnits.SelectedRows)
                {
                    sb.AppendFormat("   {0}", rowItem.Cells[ColumnIndex.Name].Value);
                    sb.AppendLine();
                }

                result = KryptonMessageBox.Show(sb.ToString(), "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }

            return result;
        }

        private void DisplayUnitData(Unit unit)
        {
            if (unit != null)
            {
                this.kdgvUnits.Rows.Add(unit.Id, unit.Name);
            }
        }

        private void AddOrUpdateUnit(Unit unit)
        {
            if (unit != null)
            {
                Unit existingUnit = this.listOfUnits.FirstOrDefault(item => (item.Id == unit.Id));
                if (existingUnit == null)
                {
                    this.listOfUnits.Add(unit);
                    this.DisplayUnitData(unit);
                }
                else
                {
                    existingUnit = unit;
                    this.UpdateUnitData(unit);
                }
            }
        }

        private void UpdateUnitData(Unit unit)
        {
            if (unit != null)
            {
                foreach (DataGridViewRow rowItem in this.kdgvUnits.Rows)
                {
                    if (unit.Id.Equals(rowItem.Cells[ColumnIndex.Id].Value))
                    {
                        rowItem.Cells[ColumnIndex.Name].Value = unit.Name;

                        break;
                    }
                }
            }
        }

        private void btnAddUnit_Click(object sender, EventArgs e)
        {
            using (var unitForm = new UnitFormEdit()
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = unitForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.AddOrUpdateUnit(unitForm.SelectedUnit);
                }
            }
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.listOfUnitsToDelete != null)
                {
                    foreach (Unit unitItem in this.listOfUnitsToDelete)
                    {
                        unitItem.Delete();
                    }
                }

                if (this.listOfUnits != null)
                {
                    foreach (Unit unitItem in this.listOfUnits)
                    {
                        unitItem.Save();
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
                this.Dispose();

                GC.SuppressFinalize(this);
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.No;
                _logger.Error("Error while saving changes", ex);
            }
        }

        private void kdgvUnits_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridViewCell modifiedCell = this.kdgvUnits.Rows[e.RowIndex].Cells[e.ColumnIndex];

                int unitId = Convert.ToInt32(this.kdgvUnits.Rows[e.RowIndex].Cells[ColumnIndex.Id].Value);
                Unit selectedUnit = this.listOfUnits.FirstOrDefault(item => item.Id == unitId);

                switch (e.ColumnIndex)
                {
                    case ColumnIndex.Name:
                        selectedUnit.Name = Convert.ToString(modifiedCell.Value);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat(ex, "Error while editing cell: {0}", e.ColumnIndex);
            }
        }

        private void kdgvUnits_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            int id = Convert.ToInt32(e.Row.Cells[ColumnIndex.Id].Value);
            Unit unitItem = this.listOfUnits.FirstOrDefault(item => (item.Id == id));

            if (this.listOfUnitsToDelete == null)
            {
                this.listOfUnitsToDelete = new List<Unit>();
            }
            this.listOfUnitsToDelete.Add(unitItem);
            this.listOfUnits.Remove(unitItem);
        }

        private void kdgvUnits_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (this.ConfirmRemoveUnits() != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ConfirmRemoveUnits() == DialogResult.Yes)
            {
                foreach (DataGridViewRow rowItem in this.kdgvUnits.SelectedRows)
                {
                    this.kdgvUnits.Rows.Remove(rowItem);

                    int id = Convert.ToInt32(rowItem.Cells[ColumnIndex.Id].Value);
                    Unit unitItem = this.listOfUnits.FirstOrDefault(item => (item.Id == id));

                    if (this.listOfUnitsToDelete == null)
                    {
                        this.listOfUnitsToDelete = new List<Unit>();
                    }
                    this.listOfUnitsToDelete.Add(unitItem);
                    this.listOfUnits.Remove(unitItem);
                }
            }
        }
    }
}
